package cn.initcap.designpattern.pattern.creational.singleton;

import java.io.Serializable;

/**
 * @author initcap
 * @date 2018/8/28 AM9:09
 */
public class HungrySingleton implements Serializable, Cloneable {

    private final static HungrySingleton HUNGRY_SINGLETON;

    static {
        HUNGRY_SINGLETON = new HungrySingleton();
    }

    /**
     * 只有在类加载，就进行初始化的使用这个方式才能防止反射攻击
     */
    private HungrySingleton() {
        if (HUNGRY_SINGLETON != null) {
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }

    public static HungrySingleton getInstance() {
        return HUNGRY_SINGLETON;
    }

    /**
     * 这里是用来防止序列化攻击的
     *
     * @return
     * @see java.io.ObjectInputStream 1807行，使用反射调用了readResolve方法；
     */
    private Object readResolve() {
        return HUNGRY_SINGLETON;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return getInstance();
    }
}
